package com.register.controller;

import com.register.pojo.QRDepot;
import com.register.pojo.QRUserAndDepot;
import com.register.pojo.SysUsers;
import com.register.service.impl.QRDepotServiceImpl;
import com.register.service.impl.QRUserAndDepotServiceImpl;
import com.register.service.impl.UserServiceImpl;
import com.register.util.CsvImportUtil;
import com.register.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/qruseranddepot")
public class QRUserAndDepotController {

    @Autowired
    QRUserAndDepotServiceImpl qrUserAndDepotService;
    @Autowired
    QRDepotServiceImpl qrDepotService;
    @Autowired
    UserServiceImpl userService;

    //获取 用户与场站对应关系 列表  type为按照类型排序  0 是按照用户id  1是按照场站id
    @GetMapping("/list")
    public String list(Model model,Integer type){

        List<Map<String,Object>> lists = qrUserAndDepotService.getList(type);
        List<SysUsers> users  = userService.list();
        List<QRDepot> qrDepots = qrDepotService.list();
        Map<String,Object>maps = new HashMap<>();
        maps.put("users",users);
        maps.put("qrDepots",qrDepots);
        maps.put("usersAndQrdepots",lists);

        model.addAttribute("result",Result.ok(maps));
        return "qrUserAndDepotList";
    }
    //添加场站与用户关系
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody QRUserAndDepot qrUserAndDepot){

        qrUserAndDepotService.save(qrUserAndDepot);
        return  Result.ok();
    }
    //删除场站与用户关系
    @GetMapping("/delete")
    @ResponseBody
    public Result delete(int id){

        qrUserAndDepotService.removeById(id);
        return Result.ok();
    }
    //上传文件 将文件文件解析  创建用户与场站  建立对应关系
    @PostMapping("/uploadFile")
    @ResponseBody
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws IOException {

        //上传文件 并解析  过程：1、解析文件 2、验证是否存在本行场站与用户,如果不存在责创建 3、建立对应关系
        InputStream inputStream = file.getInputStream();
        List<List<String>>lists =  CsvImportUtil.readCSV(inputStream,6);
        for (int i = 0 ; i < lists.size() ; i++){

            //System.out.println(lists.get(i).get(0));
            //调用添加对应关系函数
            qrUserAndDepotService.addUserAndDepot(lists.get(i));
        }
        //验证错误日志、检测 填入信息是否填报
        return Result.ok();
    }

}
